﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataAccess.DbHelper;
using System.Collections.Generic;
using SubSonic.Query;
using DataModel;
using SCM.Logic;
using Common;
using ExtAspNet;

namespace Web.Accounting
{
    public partial class Invoice : System.Web.UI.Page
    {
        List<string> _order = null;
        string _reconciliationNo = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            _order = new List<string>();
            //_order.Add(D_Invoice.InvoiceNoColumn);
            if (String.IsNullOrEmpty(Request.QueryString["ReconciliationNo"]) == false)
            {
                _reconciliationNo = Request.QueryString["ReconciliationNo"];
            }
            else
            {
                Alert.Show("付款单No取得失败！", "错误");
                ActiveWindow.GetHideReference();
                return;
            }
            if (Page.IsPostBack == false)
            {
                lblReconcilationNo.Text = _reconciliationNo;

                SetControl();
                //绑定税率下拉菜单
                //TaxType.DataSource = M_Master.All().ToList();
                //TaxType.DataTextField = M_Master.TaxTypeNameColumn;
                //TaxType.DataValueField = M_Master.TaxTypeCodeColumn;
                //TaxType.DataBind();

            }


        }
        private void SetControl()
        {
            var reconcInst = D_Reconciliation.SingleOrDefault(x=> x.ReconciliationNo == _reconciliationNo);
            if (reconcInst == null)
            {
                Alert.Show("付款单信息取得失败！","错误");
                ActiveWindow.GetHideReference();
                return;
            }
            //当前开票总金额
            lblPaidPrice.Text = String.Format("{0:f2}",reconcInst.PaidPrice);
            //应付款金额
            lblTotalPrice.Text = String.Format("{0:f2}", reconcInst.TotalPrice);
            //还需录入
            lblNeededPrice.Text = String.Format("{0:f2}", (reconcInst.TotalPrice-reconcInst.PaidPrice));
            if (reconcInst.PaidPrice == reconcInst.TotalPrice)
            {
                btnSendToChecker.Enabled = true;
            }
            else
                btnSendToChecker.Enabled = false;
            //绑定数据
            BindDataGrid();

        }
        private void BindDataGrid()
        {
            List<ConditionHelper.SqlqueryCondition> wheres = InquiryCondition();
            D_InvoiceBll.GetInstence().BindGrid(GridResult, GridResult.PageIndex + 1, GridResult.PageSize, wheres, _order);
        }


        private List<ConditionHelper.SqlqueryCondition> InquiryCondition()
        {
            var list = new List<ConditionHelper.SqlqueryCondition>();
            list.Add(new ConditionHelper.SqlqueryCondition(ConstraintType.And, D_Invoice.ReconciliationNoColumn, Comparison.Equals, _reconciliationNo));
            return list;
        }

        /// <summary>
        /// 发票修改保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Submit_Click(object sender, EventArgs e)
        {
            var reconcInst = D_Reconciliation.SingleOrDefault(x => x.ReconciliationNo == _reconciliationNo);

            //输入错误检查
            if (txtInvoiceNo.Text.Trim()!= string.Empty && txtInvoiceNo.Text.Trim().Length>8)
            {
                Alert.Show("请输入正确发票号");
                return;
            }
            //存数据
            var invoice = D_Invoice.SingleOrDefault(x => x.InvoiceNo == txtInvoiceNo.Text.Trim() && x.ReconciliationNo == _reconciliationNo);
            if (invoice == null)
            {
                //新发票信息作成
                invoice = new D_Invoice();
                invoice.InvoiceNo = txtInvoiceNo.Text.Trim();
                invoice.ReconciliationNo = _reconciliationNo;
            }
            //else //更新已有
            //{ 
            //}
            //发票信息设定
            invoice.InvoiceType = txtInvoiceType.Text.Trim();
            invoice.InvoiceDate = DatePickerInvoiceDate.SelectedDate.Value;
            invoice.TaxType = Convert.ToDecimal(ddlTaxType.SelectedValue);
            invoice.ValueAddedTax = Convert.ToDecimal(txtValueAddedTax.Text.Trim());
            invoice.Price = Convert.ToDecimal(txtPrice.Text.Trim());
            invoice.TotalPrice = Convert.ToDecimal(txtTotalPrice.Text.Trim());
            invoice.memo = TextAreaMemo.Text.Trim();
            try
            {
                invoice.Save();
                //更新付款单状态为,编辑发票
                UpdatePaidPriceAndStatus();
            }
            catch (Exception ex)
            {
                Alert.Show("发票信息保存失败。请再试一次");
                LogHelper.Error(string.Format("{0}付款单{1}的发票录入,发票号{2},{3},{4},{5},{6},{7}", 
                                                HttpContext.Current.User.Identity.Name, 
                                                _reconciliationNo,
                                                txtInvoiceNo.Text,
                                                DatePickerInvoiceDate.SelectedDate.Value.ToShortDateString(),
                                                ddlTaxType.SelectedValue,
                                                txtValueAddedTax.Text,
                                                txtPrice.Text,
                                                txtTotalPrice.Text), ex);
                return;
            }


            //绑定数据
            SetControl();
        }

        protected void btnSendToChecker_Click(object sender, EventArgs e)
        {
            // 1. 这里放置保存数据的逻辑
            
            try
            {
                var reconcInst = D_Reconciliation.SingleOrDefault(x => x.ReconciliationNo == _reconciliationNo);
                //更新已填发票金额(DB的触发器中处理)
                //更新付款单状态为,发票已提交
                reconcInst.StatusCode = Convert.ToInt32(Common.DBMaster.ReconciliationStatus.SendToChecker);
                reconcInst.Save();

            }
            catch (Exception ex)
            {

                Alert.Show("更新付款单状态失败。");
                LogHelper.Error(string.Format("{0}付款单{1}的提交所有发票给对帐员",
                                                HttpContext.Current.User.Identity.Name,
                                                _reconciliationNo), ex);
            }

            // 2. 关闭本窗体，然后刷新父窗体
            PageContext.RegisterStartupScript(ActiveWindow.GetHideReference());
        }

        protected void GridResult_RowCommand(object sender, GridCommandEventArgs e)
        {
            var keys = GridResult.Rows[e.RowIndex].DataKeys;
            var invoice = D_Invoice.SingleOrDefault(x => x.InvoiceNo == Convert.ToString(keys[0]) && x.ReconciliationNo == _reconciliationNo);
            //修改
            if (e.CommandName =="Change")
            {
                //修改内容设定
                txtInvoiceNo.Text = invoice.InvoiceNo;
                txtInvoiceType.Text = invoice.InvoiceType;
                DatePickerInvoiceDate.Text = invoice.InvoiceDate.ToShortDateString();
                ddlTaxType.SelectedValue = Convert.ToString(invoice.TaxType);
                txtValueAddedTax.Text = Convert.ToString(invoice.ValueAddedTax);
                txtPrice.Text = Convert.ToString(invoice.Price);
                txtTotalPrice.Text = Convert.ToString(invoice.TotalPrice);
                TextAreaMemo.Text = invoice.memo;
                
            }
            //删除
            if (e.CommandName == "Delete")
            {
                invoice.Delete();
                UpdatePaidPriceAndStatus();
                SetControl();
            }
        }


        /// <summary>
        /// 更新已填发票金额和更改状态
        /// </summary>
        private void UpdatePaidPriceAndStatus()
        {
            var reconcInst = D_Reconciliation.SingleOrDefault(x => x.ReconciliationNo == _reconciliationNo);

            //更新已填发票金额
            var invoices = reconcInst.D_Invoice.ToList();
            Decimal decPaid = 0;
            foreach (var iv in invoices)
            {
                decPaid += iv.TotalPrice;
            }

            reconcInst.PaidPrice = decPaid;
            //更新付款单状态为,发票未编辑，请填写
            if (reconcInst.D_Invoice.ToList().Count == 0)
            {
                reconcInst.StatusCode = Convert.ToInt32(Common.DBMaster.ReconciliationStatus.NotInovice);
            }
            else
                reconcInst.StatusCode = Convert.ToInt32(Common.DBMaster.ReconciliationStatus.InputtedInvoice);

            reconcInst.Save();
        }

    }

}
